<template>
  <div class="el-icon-picker_con">
    <el-popover v-model:visible="showPopv" placement="bottom-start" :width="440" trigger="click">
      <template #reference>
        <el-input :model-value="modelValue" :prefix-icon="modelValue" placeholder="请选择图标" readonly/>
      </template>
      <div class="el-icon-picker">
        <el-input v-model="filterVal" class="filter_input" placeholder="输入图标查询" :suffix-icon="Search" @input="inputFilter"/>
        <div class="icon_con">
          <component v-for="icon in iconList" :key="icon" class="icon" :class="{ icon, 'icon-active': icon === modelValue }" :is="icon" @click="chooseIcon(icon)"/>
        </div>
      </div>
    </el-popover>
    <el-button class="el-icon-clear" circle text size="small" :icon="Close" v-if="modelValue" title="清除" @click="clearPicker"/>
  </div>
</template>

<script setup>
import {getCurrentInstance, ref, watch} from 'vue'
import {Close, Search} from '@element-plus/icons-vue'

// 获取全局挂载
const globalProperties = getCurrentInstance().appContext.config.globalProperties

const props = defineProps({
  modelValue: {
    type: String
  }
})

let filterVal = ref('')
const emit = defineEmits(['update:modelValue'])
let showPopv = ref(false)
let iconList = ref([])

const inputFilter = (val) => {
  if (val) {
    iconList.value = globalProperties.$icons.filter((item) => item.toLowerCase().indexOf(val.toLowerCase()) !== -1)
  } else {
    iconList.value = [].concat(globalProperties.$icons)
  }
}

const chooseIcon = (icon) => {
  emit('update:modelValue', icon)
  showPopv.value = false
}

const clearPicker = () => {
  emit('update:modelValue', '')
}

watch(() => showPopv.value, (newVal, oldVal) => {
  if (newVal) {
    filterVal.value = ''
    inputFilter()
  }
})
</script>

<style scoped>
.el-icon-picker_con {
  position: relative;
  width: 100%;
}

.el-icon-picker {
  height: 256px;
  overflow-y: scroll;
}

.el-icon-picker .icon {
  display: inline-block;
  width: 20px;
  height: 20px;
  color: #333;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  text-align: center;
  line-height: 45px;
  margin: 10px;
}

.el-icon-picker .icon:hover {
  color: var(--el-color-primary);
}

.el-icon-picker .icon-active {
  color: var(--el-color-primary);
}

.el-icon-picker .filter_input {
  width: 100%;
  padding: 0 12px;
  box-sizing: border-box;
  margin-bottom: 3px;
}

.el-icon-picker .icon_con {
  height: calc(100% - 39px);
}

.el-icon-clear {
  position: absolute;
  top: 50%;
  right: 6px;
  transform: translateY(-50%);
}
</style>
